package com.example.springcloud.controller;

import com.example.springcloud.entity.Payment;
import com.example.springcloud.service.PaymentService;
import com.example.springcloud.utils.Constant;
import com.example.springcloud.utils.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 测试 mybatis-plus 的增删改查以及 web 环境
 */
@RestController
@Slf4j
@RequestMapping(value = "/payment")
public class PaymentController {

    /**
     * 注入 service
     */
    @Resource
    PaymentService paymentService;
    /**
     * The Discovery client.
     */
    @Resource
    DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    /**
     * 查询所有 payment
     *
     * @return the list
     */
    @RequestMapping(value = "/get/All")
    public ResultEntity<List<Payment>> selectAll() {

        return ResultEntity.commonResult(Constant.RESPONSE_CODE_200, "成功获取数据，port = " + serverPort, paymentService.getAllPayments());

    }

    @GetMapping("/testGatewayFilter")
    public String testGatewayFilter(@RequestParam("username") String username) {

        return "欢迎用户【" + username + "】 port = " + serverPort;

    }

    /**
     * 通过 id 获取订单
     *
     * @param id the id
     * @return the by id
     */
    @RequestMapping(value = "/get/{id}")
    public ResultEntity<Payment> getById(@PathVariable(value = "id") Integer id) {

        return ResultEntity.commonResult(Constant.RESPONSE_CODE_200, "成功获取数据，port = " + serverPort, paymentService.getById(id));
    }

    /**
     * 新增一条订单
     *
     * @param payment the payment
     * @return the result entity
     */
    @PostMapping(value = "/create")
    public ResultEntity<Boolean> create(@RequestBody Payment payment) {

        // 由于一些已知的bug暂时无法解决，所以在此添加一个验证主键是否重复的步骤
        if (paymentService.getById(payment.getId()) == null) {
            return ResultEntity.commonResult(Constant.RESPONSE_CODE_200, "成功插入数据，port = " + serverPort, paymentService.save(payment));

        }
        return ResultEntity.failedWithoutData(Constant.RESPONSE_CODE_500, "主键重复，插入失败，port = " + serverPort);
    }

    /**
     * 查询正在运行的微服务名
     *
     * @return the list
     */
    @GetMapping(value = "/discovery")
    public ResultEntity<List<String>> discover() {

        return new ResultEntity<>(Constant.RESPONSE_CODE_200, "成功获取服务名，port = " + serverPort, discoveryClient.getServices());
    }

    @GetMapping("/feignTimeoutTest")
    public String feignTimeoutTest() throws InterruptedException {

        TimeUnit.SECONDS.sleep(5);
        return serverPort;
    }

    @GetMapping("/zipkin")
    public String testZipkin() {

        return "success";
    }

}
